import store from "@/store";
import Cookies from "js-cookie";
import { MessageBox } from "element-ui";
import router from "@/router";
let { NODE_ENV } = process.env;
import { appId } from "@/utils/config.js";

/**下载文件(.txt/.jpg/.csv...)
 * @param {string} :url：地址
 * @param {string} :filename：下载文件的名字
 * @param {string} :strMimeType：表示文件的mineType
 * @return:void
 */
export function download(url, filename, strMimeType) {
  var x = new XMLHttpRequest();
  x.open("GET", url, true);
  x.responseType = "blob";
  x.onload = function (e) {
    var url = window.URL.createObjectURL(x.response);
    var a = document.createElement("a");
    a.href = url;
    a.download = filename;
    a.click();
  };
  x.send();
}
/**
 * 用户角色权限能力 如果是operate或者admin 就是管理员权限了
 * @returns {Boolean}
 */
export function getCodeSession() {
  //开发环境权限为admin
  if (NODE_ENV === "development") {
    return true;
  }
  let codeSessionRole = Cookies.get(`CORE_SESSION_ROLE${appId[NODE_ENV]}`) || "";
  let codeSession = codeSessionRole.split("-");
  return codeSession.includes("operate") || codeSession.includes("admin");
}
/**
 *
 * @param {object}
 * @param {function} 回调函数
 *
 */
export function $confirm(params, callback, catchCallback) {
  let { content, title, confirmButtonText, cancelButtonText, type } = params;
  MessageBox.confirm(content || "此操作将永久删除, 是否继续?", title || "提示", {
    confirmButtonText: confirmButtonText || "确定",
    cancelButtonText: cancelButtonText || "取消",
    type: type || "warning",
  })
    .then(() => {
      arguments.length == 1 ? params() : callback(); //如果参数是一个，直接执行回调函数
    })
    .catch(() => {
      catchCallback?.();
    });
}
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return d.getMonth() + 1 + "月" + d.getDate() + "日" + d.getHours() + "时" + d.getMinutes() + "分";
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}
/**
 *处理打来新窗口逻辑
 * @param {params} 路由动态地址
 * @param {target} 回调函数
 *
 */
export function $router(params, target) {
  if (target === "_blank") {
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  } else {
    router.push(params);
  }
}
/**
 * 根据字段分类和字典值，获取字典label
 * @param {number} dicType
 * @param {string} dicVal
 * @returns
 */
// export function getDicLabel(dicType, dicVal) {
//   let dicLabel = "";
//   try {
//     dicLabel = store.state.dictionary[dicType].filter((e) => e.value.toString() == dicVal.toString())[0].label;
//   } catch (error) {}
//   return dicLabel;
// }

/**
 * 根据字段分类和字典值，获取字典label
 * @param {number | array} dicType
 * @param {string} dicVal
 * @param {string} propName 匹配哪个字段
 * @returns
 */
//获取字典匹配的label值
export function getDicLabel(dicType, dicVal, propName) {
  let dicData = [];
  if (Array.isArray(dicType)) {
    dicData = dicType.filter((item) => {
      return (item[propName] || item.value) == dicVal;
    });
  } else {
    dicData = store.state.dictionary[dicType].filter((item) => {
      return (item[propName] || item.value) == dicVal;
    });
  }
  return (dicData.length > 0 && dicData[0].label) || "";
}
